//
//  ST_BTUserInfoManager+Modify.swift
//  btvideo
//
//  Created by Jason on 2021/11/2.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import Foundation
import RealmSwift
import SwiftyJSON

extension ST_BTUserInfoManager{
    /** require execute in main thread
     */
    func modify_current_account(pairsModel:ST_PairsMyCenterHeaderViewModel){
        
        
        let realm = try! Realm()

        try! realm.write {
            current_account_info?.userinfo?.age = pairsModel.age
            current_account_info?.userinfo?.nickname = pairsModel.nickname
            if let avatar = pairsModel.particularArray.first?.imageUrl{
                current_account_info?.userinfo?.avatar = avatar
            }
        }

        ST_BTLaunchController.shared.update_mycenter_tab_avatar()
    }
    
    /** require execute in main thread
    */
    func modify_member_expire(value:Int){
        
        let realm = try! Realm()
       
        try! realm.write {
            
            current_account_info?.userinfo?.vip_expire = value
        }
        
        NotificationCenter.default.post(name: Notification.Name.in_pur_status_success, object: nil)
    }
    
    /** require execute in main thread
    */
    func modify_sweet_coin(value:Float){
        
        let realm = try! Realm()
       
        try! realm.write {
            current_account_info?.userinfo?.remoteSweetCoin = value
        }
        
        if value < 25 && current_account_info?.userinfo?.sex == .male{
            ST_LiveBeautyWidget.shared.cancel_match_game()
        }
        
        NotificationCenter.default.post(name: Notification.Name.modifyCoin, object: nil)
    }
    
    
    /** require execute in main thread
    */
    func modify_consume_coin(offsetValue:Float){
        
        
        print("重点 bug  开始 扣币啦啦啦啦local =",offsetValue,"---remoteSweetCoin",current_account_info?.userinfo?.remoteSweetCoin ?? "错误")
        
        let realm = try! Realm()
       
        try! realm.write {
            current_account_info?.userinfo?.localConsumeSweetCoin += offsetValue
        }
    }
    
    func modify_free_talk_count(value:Int){
        
        let realm = try! Realm()
       
        try! realm.write {
            
            current_account_info?.userinfo?.freeTalkCount = value
        }
    }
    
    /**
     发及时消息   return 【int == 0 免费 ，int == 1 收费】
     */
    func send_tnstant_message(consumeCoin:Float,reduceExecute:Bool = false) -> Int? {
      
        guard let user = get_current_user_in_current_thread()?.userinfo else { return nil }
        
        if user.sweet_coin >= consumeCoin{
            
            if reduceExecute {
                
                print("扣分问题：之前---",user.sweet_coin)
                
                modify_sweet_coin(value: user.sweet_coin - consumeCoin)
                
                print("扣分问题：之后---",user.sweet_coin)
            }
            
            return 1
        }
        
        if user.freeTalkCount > 0{
            
            if reduceExecute {
                
                
                
                modify_free_talk_count(value: user.freeTalkCount - 1)
                
                
            }
            
            return 0
        }
        
        return nil
        
    }
    
    
    /** require execute in main thread
    */
    func modify_sweet_income(value:Double,outValue:Double){
        
        let realm = try! Realm()
       
        try! realm.write {
            
            current_account_info?.userinfo?.income = value
            
            current_account_info?.userinfo?.income_out = value
            
            current_account_info?.userinfo?.incomeUpdateDate = Date()
        }
        
        NotificationCenter.default.post(name: Notification.Name.modifyIncomeCoin, object: nil)
    }
    
    
    /**
     增加\(Defaults[.PandaStr])「红包，守护，礼物，道具 等」
     */
    func increase_income(value:Double,msgSendDate:Date){
        
        guard let income = current_account_info?.userinfo?.income,let updateDate = current_account_info?.userinfo?.incomeUpdateDate, msgSendDate > updateDate else { return  }
        
        let v = income + value
        
        modify_sweet_income(value: v, outValue: v/10.0)
        
    }
    
    /** require execute in main thread
     */
    func modify_curr_base_info(json:JSON){
        
        let realm = try! Realm()
       
        try! realm.write {
            
            current_account_info?.userinfo?.register_version = json["register_version"].stringValue
            
            current_account_info?.userinfo?.register_time = json["register_time"].intValue
            
            current_account_info?.userinfo?.personal_want_name = json["personal_want_name"].stringValue
            
            current_account_info?.ticketPaid = json["ticket_paid"].boolValue
            
            current_account_info?.registerStep = json["register_type"].intValue == 1 ? .longer : .shorter
            
        }
    }
    
    /** require execute in main thread
     */
    func modify_current_account(aiCenterJson:JSON){
        
        
        let realm = try! Realm()
        
//        let lastVip = current_account_info?.userinfo?.vip_expire
        
        let lastCoin = current_account_info?.userinfo?.sweet_coin
        
        let lastIncomCoin = current_account_info?.userinfo?.income
        
        try! realm.write {
            
            current_account_info?.userinfo?.nickname = aiCenterJson["nickname"].stringValue
            
            current_account_info?.userinfo?.avatar = aiCenterJson["avatar"].stringValue
            
            current_account_info?.userinfo?.vip_expire = aiCenterJson["vip_expire"].intValue
            
            current_account_info?.userinfo?.freeTalkCount = aiCenterJson["free_quick_talk_num"].intValue
            
        }
        
        /* vip暂时不影响 消息列表 刷新 取消
        if let last = lastVip{
//            vip 状态更新 刷新 消息列表
            if last != aiCenterJson["vip_expire"].intValue{
                ST_BTMessageController.shared.refresh_all_data()
            }
        }else{
            ST_BTMessageController.shared.refresh_all_data()
        }
        */
        if let last = lastCoin,last == aiCenterJson["sweet_currency"].floatValue{
            print("")
        }else{
            self.modify_sweet_coin(value: aiCenterJson["sweet_currency"].floatValue)
        }
        
        
        if let last = lastIncomCoin,last == aiCenterJson["income"].doubleValue{
            print("")
        }else{
            
            self.modify_sweet_income(value: aiCenterJson["income"].doubleValue, outValue: aiCenterJson["income_out"].doubleValue)
        }

        ST_BTLaunchController.shared.update_mycenter_tab_avatar()
        
    }
    
    /** require execute in main thread
     */
    func modify_current_account(receiptResponse:JSON){
        
        let realm = try! Realm()
        
        try! realm.write {
            
            current_account_info?.userinfo?.vip_expire = receiptResponse["vip_expire"].intValue
            
            current_account_info?.userinfo?.freeTalkCount = receiptResponse["free_quick_talk_num"].intValue
            
            current_account_info?.extra_data?.like_times = receiptResponse["like_times"].intValue
            
            current_account_info?.ticketPaid = receiptResponse["ticket_paid"].boolValue
            
        }
        
        let lastCoin = current_account_info?.userinfo?.sweet_coin
        
        if let last = lastCoin,last == receiptResponse["sweet_currency"].floatValue{
            print("")
        }else{
            self.modify_sweet_coin(value: receiptResponse["sweet_currency"].floatValue)
        }
    }
    
    
    
    /** require execute in main thread
     */
    func modify_current_account(newValue:UserPreviewModel){
        

        var willUpdate = false
        if current_account_info?.userinfo?.gender != newValue.user.gender{
            willUpdate = true
        }
//                更新用户信息、会员状态
        let realm = try! Realm()
    
        try! realm.write {
            
            current_account_info?.userinfo?.cover_video = newValue.user.cover_video
            current_account_info?.userinfo?.gender = newValue.user.gender
            current_account_info?.userinfo?.city_name = newValue.user.city_name
            current_account_info?.userinfo?.age = newValue.user.age
            current_account_info?.userinfo?.birth = newValue.user.birth
            current_account_info?.userinfo?.avatar = newValue.user.avatar
            current_account_info?.userinfo?.marriage = newValue.user.marriage
            current_account_info?.userinfo?.constellation = newValue.user.constellation
            current_account_info?.userinfo?.nickname = newValue.user.nickname
            current_account_info?.userinfo?.like_number = newValue.user.like_number
            current_account_info?.userinfo?.cover_video_img = newValue.user.cover_video_img
            current_account_info?.userinfo?.sign = newValue.user.sign
            
            current_account_info?.extra_data?.super_like = newValue.extra_data.super_like
            current_account_info?.extra_data?.super_hot = newValue.extra_data.super_hot
            current_account_info?.extra_data?.expiration_time = newValue.extra_data.expiration_time
            
            current_account_info?.extra_data?.same_city_expire = newValue.extra_data.same_city_expire
            
            current_account_info?.extra_data?.like_times = newValue.extra_data.like_times
            
            current_account_info?.extra_data?.slide_times = newValue.extra_data.slide_times
            
            current_account_info?.extra_data?.video_status = newValue.extra_data.video_status
        }
        
        
        
        if willUpdate {
            NotificationCenter.default.post(name: NSNotification.Name.gender_switched, object: nil)
        }
        
        
    }
    
    /// 门槛限制
    func confined_to_ticket()->Bool{
        
        ///已经跳转一次门槛页面 不在跳转
        if self.ticket_controller != nil{
            return false
        }
        
        guard let account = current_account_info,let user = account.userinfo else { return true }
        
        if account.registerStep == .longer,user.sex == .male,account.ticketPaid == false{
            return true
        }
        
        return false
        
    }
    
}
